import RightContent from '@/components/RightContent';
import { getCanDiscount } from '@/services/common/api';
import {
  getCurrentUserActionList,
  getCurrentUserMenus,
  currentUser as queryCurrentUser,
} from '@/services/user/login';
import type { Settings as LayoutSettings, MenuDataItem } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RequestConfig, RunTimeLayoutConfig } from 'umi';
import { history } from 'umi';
// @ts-ignore
import { showMsg } from '@/utils/utils';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { isMobile } from 'react-device-detect';
moment.locale('zh-cn');

const loginPath = '/user/login';
const padLoginPath = '/user/pad/login';
const pcLoginPath = '/user/open/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

interface MenuItem {
  menu_id: string;
  menu_name: string;
  children: MenuItem[];
};

interface InitialStateType {
  settings: Partial<LayoutSettings>;
  currentUser?: USERAPI.CurrentUser;
  fetchUserInfo: () => Promise<USERAPI.CurrentUser | undefined>;
  fetchUserMenus?: () => Promise<USERAPI.UserMenu[]>;
  actionList?: any[];
  buttonIdList?: string[];
  menus?: MenuItem[];
  fetchCanDiscount?: () => Promise<USERAPI.CurrentUser | undefined>;
  canDiscount?: boolean;
  canAll?: boolean;
}

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<InitialStateType> {
  const fetchCanDiscount = async () => {
    try {
      const res = await getCanDiscount();
      return res;
    } catch (error: any) {
      showMsg(error?.data?.errmsg);
      history.push(loginPath);
    }
    return false;
  }

  const fetchUserInfo = async () => {
    try {
      const currentUser = await queryCurrentUser();
      return currentUser;
    } catch (error: any) {
      showMsg(error?.data?.errmsg);
      history.push(isMobile ? padLoginPath : loginPath);
    }
    return undefined;
  };

  const fetchUserActionList = async () => {
    try {
      const actionList = await getCurrentUserActionList();
      return actionList;
    } catch (error) {
      console.log(error);
    }
    return [];
  };

  /**
   * 把后端返回的数据结构统一重命名
   * 后端结构：[{"menu_id": "200","menu_name": "库存商品管理","sub_list": [{"sub_menu_id": "204","sub_menu_name": "库存管理"}]}]
   * 转换后：[{"menu_id": "200","menu_name": "库存商品管理","children": [{"menu_id": "204","menu_name": "库存管理"}]}]
   */
  const menuObjTransform = (obj: Object): MenuItem => {
    let id = null, name = null, children: MenuItem[] = [];
    for (const key in obj) {
      if (key.includes('_id') && typeof obj[key] === 'string') {
        id = obj[key];
        continue;
      }
      if (key.includes('_name') && typeof obj[key] === 'string') {
        name = obj[key];
        continue;
      }
      if (key.includes('_list') && Array.isArray(obj[key])) {
        children = menuArrTransform(obj[key]);
        continue;
      }
    }
    return { menu_id: id, menu_name: name, children };
  };

  const menuArrTransform = (arr: Object[]): MenuItem[] => {
    if (!Array.isArray(arr)) {
      return [];
    }
    return arr.flatMap(obj => menuObjTransform(obj));
  };

  const fetchUserMenus = async () => {
    try {
      const menus = await getCurrentUserMenus();
      return menuArrTransform(menus);
    } catch (error) {
      console.log(error);
    }
    return [];
  };

  // 如果是登录页面，不执行
  const pathname = history.location.pathname;
  if (pathname !== loginPath && pathname !== padLoginPath && pathname !== pcLoginPath) {
    try {
      const currentUser = await fetchUserInfo();
      if (!currentUser) {
        return {
          fetchUserInfo,
          settings: {}
        };
      }

      const menus = await fetchUserMenus();
      const canDiscount = await fetchCanDiscount();
      const actionList: any[] = await fetchUserActionList();

      const buttonIdList = actionList.map((item) => {
        return item.button_id;
      });
      localStorage.setItem('buttonIdList', JSON.stringify(buttonIdList));
      return {
        fetchUserInfo,
        fetchCanDiscount,
        canDiscount: canDiscount.is_discount === 'Y',
        canAll: canDiscount.is_all === 'Y',
        currentUser,
        // actionList,
        buttonIdList,
        menus,
        settings: {}
      };
    } catch (error: any) {
      console.log('error', error);
      showMsg(error?.data?.errmsg);
    }
  }
  return {
    fetchUserInfo,
    fetchCanDiscount,
    settings: {}
  };
}


/**
 * 异常处理程序
    200: '服务器成功返回请求的数据。',
    201: '新建或修改数据成功。',
    202: '一个请求已经进入后台排队（异步任务）。',
    204: '删除数据成功。',
    400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
    401: '用户没有权限（令牌、用户名、密码错误）。',
    403: '用户得到授权，但是访问是被禁止的。',
    404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
    405: '请求方法不被允许。',
    406: '请求的格式不可得。',
    410: '请求的资源被永久删除，且不会再得到的。',
    422: '当创建一个对象时，发生一个验证错误。',
    500: '服务器发生错误，请检查服务器。',
    502: '网关错误。',
    503: '服务不可用，服务器暂时过载或维护。',
    504: '网关超时。',
 //-----English
    200: The server successfully returned the requested data. ',
    201: New or modified data is successful. ',
    202: A request has entered the background queue (asynchronous task). ',
    204: Data deleted successfully. ',
    400: 'There was an error in the request sent, and the server did not create or modify data. ',
    401: The user does not have permission (token, username, password error). ',
    403: The user is authorized, but access is forbidden. ',
    404: The request sent was for a record that did not exist. ',
    405: The request method is not allowed. ',
    406: The requested format is not available. ',
    410':
        'The requested resource is permanently deleted and will no longer be available. ',
    422: When creating an object, a validation error occurred. ',
    500: An error occurred on the server, please check the server. ',
    502: Gateway error. ',
    503: The service is unavailable. ',
    504: The gateway timed out. ',
 * @see https://beta-pro.ant.design/docs/request-cn
 */
const authHeaderInterceptor = (url: string, options: any) => {
  const { headers } = options;
  const authHeader = {
    'Oper-Token': localStorage.getItem('Oper-Token'),
    Action_Id: headers?.Action_Id,
  };

  if (!headers?.Action_Id) {
    delete authHeader.Action_Id;
  }
  // try {
  //   // document.getElementsByClassName('bg_logo_zoe')[0].style='z-index: 0';
  //   window.parent.document.getElementsByClassName("bg_logo_zoe")[0].style='z-index: 0'
  //   console.log('已将bg_logo_zoe设置', document.getElementsByClassName('bg_logo_zoe'));
  // } catch (error) {
  //   console.log('找不到bg_logo_zoe', document.getElementsByClassName('bg_logo_zoe'));
  // }
  return {
    url: `${url}`,
    options: { ...options, interceptors: true, headers: authHeader },
  };
};
export const request: RequestConfig = {
  requestInterceptors: [authHeaderInterceptor],
  errorHandler: (error: any) => {
    const { /* response, */ data } = error;
    // console.log('error111', error, data);
    // const { response } = error;
    // if (!response) {
    // notification.error({
    //   description: '您的网络发生异常，无法连接服务器',
    //   message: '网络异常',
    // });
    // }
    try {
      if (data.errcode === 'BUI00007' || data.errcode === 'BUI00014') {
        localStorage.clear();
        window.location.replace('http://10.101.1.150:8108/portal/');
      }
    } catch (error) {
    }
    throw { data };
  },
};


type menuDataRenderType = (routeMenus: MenuDataItem[], userMenus: MenuItem[], menuLevel?: number) => MenuDataItem[];

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  // 当前登录的账号
  const currentUser = initialState?.currentUser || {};
  const userType = currentUser.identity_type;
  const deptLevel = currentUser.dept_level;

  const menuDataRender: menuDataRenderType = (routeMenus = [], userMenus = [], menuLevel = 1) => {
    if (userMenus.length === 0) {
      if (!isMobile && (userType === 'S' || userType === 'A')) {
        // 管理能看
        return routeMenus.filter(({ keyid }) => keyid === '000' || keyid === '001').map(rMenu => ({
          ...rMenu,
          children: (userType === 'A' ? rMenu.children : rMenu.children?.filter(({ keyid }) => keyid !== 'super'))
            ?.filter(({ dept_level }) => (!dept_level || dept_level === deptLevel))
        }));
      } else {
        // 欢迎页都能看
        return routeMenus.filter(({ keyid }) => keyid === '000');
      }
    }
    return routeMenus.map(rMenu => {
      if (rMenu.keyid === '000') {
        return rMenu;
      }
      if (isMobile && rMenu.pad !== true) {
        return {};
      }
      if (rMenu.keyid === '001') {
        if (userType === 'P' || isMobile) {
          return {};
        } else {
          return {
            ...rMenu,
            children: (userType === 'A' ? rMenu.children : rMenu.children?.filter(({ keyid }) => keyid !== 'super'))
              ?.filter(({ dept_level }) => (!dept_level || dept_level === deptLevel))
          };
        }
      }
      const keyidArr = menuLevel !== 1 ? rMenu.keyid.split(',') : [rMenu.keyid];
      const uMenu = userMenus.find(({ menu_id }) => (menuLevel === 1 && `${menu_id}_1` === rMenu.keyid) || (menuLevel !== 1 && keyidArr.indexOf(menu_id) != -1));
      if (rMenu.keyid !== '001' && !uMenu) {
        return {};
      }
      return { ...rMenu, children: menuDataRender(rMenu.children || [], uMenu?.children || [], menuLevel + 1) };
    }).filter(({ path }) => !!path);
  };

  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    onPageChange: () => {
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
      }
    },
    logo: () => 'https://preview.pro.ant.design/static/logo.f0355d39.svg',
    // menuHeaderRender: (logo,title) => <div>{logo}{title}</div>,
    menuHeaderRender: (logo, title) => (
      <div
        id="customize_menu_header"
        onClick={() => {
          // window.open('https://remaxjs.org/');
          history.push('/welcome');
        }}
      >
        <img src={require('/public/logo.png')} />
        {title}
      </div>
    ),
    menuDataRender: menuData => menuDataRender(menuData, initialState?.menus || []),
    collapsed: isMobile ? true : undefined,
    // menu:{ ...menu, loading }
    // menu: {
    //   params: {
    //     userId: initialState?.currentUser?.oper_id,
    //   },
    //   request: async (params, defaultMenuData) => {
    //     // return initialState.menus;
    //     // console.log('params', params);
    //     const menu = initialState.menus;

    //     // const localItem = {
    //     //   ...menu,
    //     //   children: menu.children ? menuDataRender(menu.children, mMenu.sub_list || []) : undefined,
    //     // };
    //     // return localItem as MenuDataItem;
    //   }
    // },
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};
